home *** CD-ROM | disk | FTP | other *** search
/ Languguage OS 2 / Languguage OS II Version 10-94 (Knowledge Media)(1994).ISO / gnu / dejagnu.lha / dejagnu-1.0.1 / expect / expect.c < prev    next >
C/C++ Source or Header  |  1993-04-26  |  53KB  |  2,107 lines

  1. /* expect.c - expect and trap commands
  2.  
  3. Written by: Don Libes, NIST, 2/6/90
  4.  
  5. Design and implementation of this program was paid for by U.S. tax
  6. dollars.  Therefore it is public domain.  However, the author and NIST
  7. would appreciate credit if this program or parts of it are used.
  8.  
  9. $Revision: 1.12 $
  10. $Date: 1993/04/26 22:54:50 $
  11.  
  12. */
  13.  
  14. #include <sys/types.h>
  15. #include <stdio.h>
  16. #include <signal.h>
  17. #include <varargs.h>
  18. #include <errno.h>
  19. #include <ctype.h>    /* for isspace */
  20. #include <time.h>    /* for time(3) */
  21. #include <setjmp.h>
  22. #include <sys/wait.h>
  23. #include "exp_conf.h"
  24.  
  25. #include "tcl.h"
  26. extern char *tclRegexpError;    /* declared in tclInt.h */
  27.  
  28. #include "string.h"
  29.  
  30. #include "regexp.h"
  31. #include "exp_rename.h"
  32. #include "exp_global.h"
  33. #include "exp_command.h"
  34. #include "exp_log.h"
  35. #include "exp_main.h"
  36. #include "exp_event.h"
  37. #include "exp_tty.h"
  38.  
  39. /* initial length of strings that we can guarantee patterns can match */
  40. int exp_default_match_max =    2000;
  41. #define INIT_EXPECT_TIMEOUT    "10"    /* in seconds */
  42.  
  43. int exp_default_parity =    TRUE;
  44.  
  45. /* user variable names */
  46. #define EXPECT_TIMEOUT        "timeout"
  47. #define EXPECT_MATCH_MAX    "match_max"
  48. #define EXPECT_OUT        "expect_out"
  49. #define SPAWN_ID_ANY_VARNAME    "any_spawn_id"
  50. #define SPAWN_ID_ANY_LIT    "-1"
  51. #define SPAWN_ID_ANY        -1
  52.  
  53. static int i_read_errno;/* place to save errno, if i_read() == -1, so it
  54.                doesn't get overwritten before we get to read it */
  55. static jmp_buf env;    /* for interruptable read() */
  56.             /* longjmp(env,1) times out the read */
  57.             /* longjmp(env,2) restarts the read */
  58. static int env_valid = FALSE;    /* whether we can longjmp or not */
  59. static int timeout;    /* seconds */
  60.  
  61. void exp_lowmemcpy();
  62. int Exp_StringMatch();
  63. int Exp_StringMatch2();
  64.  
  65. int i_read();
  66.  
  67. /*ARGSUSED*/
  68. static RETSIGTYPE
  69. sigalarm_handler(n)
  70. int n;                   /* unused, for compatibility with STDC */
  71. {
  72. #ifdef REARM_SIG
  73.     signal(SIGALRM,sigalarm_handler);
  74. #endif
  75.  
  76.     /* check env_valid first to protect us from the alarm occurring */
  77.     /* in the window between i_read and alarm(0) */
  78.     if (env_valid) longjmp(env,1);
  79. }
  80.  
  81. /* upon interrupt, act like timeout */
  82. /*ARGSUSED*/
  83. static RETSIGTYPE
  84. sigint_handler(n)
  85. int n;            /* unused, for compatibility with STDC */
  86. {
  87. #ifdef EXP_DEBUGGER
  88.     extern int exp_debugger_active;
  89. #endif
  90.  
  91. #ifdef REARM_SIG
  92.     signal(SIGINT,sigint_handler);/* not nec. for BSD, but doesn't hurt */
  93. #endif
  94.  
  95. #ifdef EXP_DEBUGGER
  96.     if (exp_debugger_active) {
  97.         /* if the debugger is active and we're reading something, */
  98.         /* force the debugger to go interactive now and when done, */
  99.         /* restart the read.  
  100.  
  101.         debugger(interp,env_valid);
  102.  
  103.         /* restart the read */
  104.         if (env_valid) longjmp(env,2);
  105.  
  106.         /* if no read is in progess, just let debugger start at */
  107.         /* the next command. */
  108.         return;
  109.     }
  110. #endif
  111.  
  112. #if 0
  113. /* the ability to timeout a read via ^C is hereby removed 8-Mar-1993 - DEL */
  114.  
  115.     /* longjmp if we are executing a read inside of expect command */
  116.     if (env_valid) longjmp(env,1);
  117. #endif
  118.  
  119.     /* if anywhere else in code, prepare to exit */
  120.     exp_exit((Tcl_Interp *)0,0);
  121. }
  122.  
  123. /* 1 ecase struct is reserved for each case in the expect command.  Note that
  124. eof/timeout don't use any of theirs, but the algorithm is simpler this way. */
  125.  
  126. struct ecase {    /* case for expect command */
  127.     int m;        /* master */
  128.     int n;        /* number of patterns */
  129.     char *pat;    /* original pattern spec */
  130.     char **patn;    /* if multiple patterns in list */
  131.     char *body;    /* ptr to body to be executed upon match */
  132. #define PAT_EOF        1
  133. #define PAT_TIMEOUT    2
  134. #define PAT_DEFAULT    3
  135. #define PAT_FULLBUFFER    4
  136. #define PAT_GLOB    5 /* glob-style pattern list */
  137. #define PAT_RE        6 /* regular expression */
  138.     int use;    /* PAT_XXX */
  139.     int glob_start;    /* start of string matched when use == PAT_GLOB */
  140.     int transfer;    /* if false, leave matched chars in input stream */
  141. #define CASE_UNKNOWN    0
  142. #define CASE_NORM    1
  143. #define CASE_LOWER    2
  144.     int Case;    /* convert case before doing match? */
  145.     regexp *re;    /* if this is 0, then pattern match via glob */
  146. #define EXP_BEFORE    1
  147. #define EXP_DURING    2
  148. #define EXP_AFTER    3
  149.     int owner;    /* one of the above */
  150. };
  151.  
  152. /* data structure for saving results of expect_before/after */
  153. struct expect_special {
  154.     char *prefix;        /* command plus blank to shove in front */
  155.                 /* of args upon finding 1 arg and recursing */
  156.     struct ecase *ecases;
  157.     int ecount;        /* count of cases */
  158.     int *masters;
  159.     int mcount;        /* number of masters */
  160.     int me;
  161. };
  162.  
  163. static struct expect_special
  164.     before = {"expect_before ", NULL, 0, NULL, 0, EXP_BEFORE},
  165.     after  = {"expect_after ",  NULL, 0, NULL, 0, EXP_AFTER};
  166.  
  167. /* remove nulls from s.  Initially, the number of chars in s is c, */
  168. /* not strlen(s).  This count does not include the trailing null. */
  169. /* returns number of nulls removed. */
  170. static int
  171. rm_nulls(s,c)
  172. char *s;
  173. int c;
  174. {
  175.     char *s2 = s;    /* points to place in original string to put */
  176.             /* next non-null character */
  177.     int count = 0;
  178.     int i;
  179.  
  180.     for (i=0;i<c;i++,s++) {
  181.         if (0 == *s) {
  182.             count++;
  183.             continue;
  184.         }
  185.         if (count) *s2 = *s;
  186.         s2++;
  187.     }
  188.     return(count);
  189. }
  190.  
  191. /* generate printable versions of random ASCII strings.  This is used by */
  192. /* cmdExpect when -d forces it to print strings it is examining. */
  193. char *
  194. printify(s)
  195. char *s;
  196. {
  197.     static int destlen = 0;
  198.     static char *dest = 0;
  199.     char *d;        /* ptr into dest */
  200.     unsigned int need;
  201.  
  202.     if (s == 0) return("<null>");
  203.  
  204.     /* worst case is every character takes 3 to printify */
  205.     need = strlen(s)*3 + 1;
  206.     if (need > destlen) {
  207.         if (dest) free(dest);
  208.         if (!(dest = malloc(need))) {
  209.             destlen = 0;
  210.             return("malloc failed in printify");
  211.         }
  212.         destlen = need;
  213.     }
  214.  
  215.     for (d = dest;*s;s++) {
  216.         if (*s == '\r') {
  217.             strcpy(d,"\\r");        d += 2;
  218.         } else if (*s == '\n') {
  219.             strcpy(d,"\\n");        d += 2;
  220.         } else if (*s == '\t') {
  221.             strcpy(d,"\\t");        d += 2;
  222.         } else if ((unsigned)*s < 0x20) { /* unsigned strips parity */
  223.             sprintf(d,"\\C%c",*s + '`');    d += 3;
  224.         } else if (*s == 0x7f) {
  225.             /* not syntactically correct, but you get the point */
  226.             strcpy(d,"\\7f");        d += 3;
  227.         } else {
  228.             *d = *s;            d += 1;
  229.         }
  230.     }
  231.     *d = '\0';
  232.     return(dest);
  233. }
  234.  
  235. /* free up any argv structures in the ecases */
  236. static void
  237. free_ecases(ecases,ecases_inuse,me)
  238. struct ecase *ecases;
  239. int ecases_inuse;
  240. int me;
  241. {
  242.     int i;
  243.     struct ecase *ec;
  244.  
  245.     for (ec=ecases,i=0;i<ecases_inuse;i++,ec++) {
  246.         if (ec->re) free((char *)ec->re);
  247.         /* individual elements of each list don't have to be freed */
  248.         /* because SplitList allocates them all from single blocks! */
  249.         if (ec->patn) free((char *)ec->patn);
  250.         if (me != EXP_DURING) {
  251.             if (ec->pat) free(ec->pat);
  252.             if (ec->body) free(ec->body);
  253.         }
  254.     }
  255.     if (ecases) free((char *)ecases);
  256. }
  257.  
  258. #if 0
  259. /* no standard defn for this, and some systems don't even have it, so avoid */
  260. /* the whole quagmire by calling it something else */
  261. static char *exp_strdup(s)
  262. char *s;
  263. {
  264.     char *news = malloc(strlen(s) + 1);
  265.     if (news) strcpy(news,s);
  266.     return(news);
  267. }
  268. #endif
  269.  
  270. /* In many places, there is no need to malloc a copy of a string, since it */
  271. /* will be freed before we return to Tcl */
  272. #define SUCCESS 0
  273. #define FAILURE 1
  274. static int
  275. save_str(lhs,rhs,me)
  276. char **lhs;    /* left hand side */
  277. char *rhs;    /* right hand side */
  278. int me;
  279. {
  280.     if ((me == EXP_DURING) || (rhs == 0)) {
  281.         *lhs = rhs;
  282.         return SUCCESS;
  283.     }
  284.     *lhs = malloc(strlen(rhs) + 1);
  285.     if (!*lhs) return FAILURE;
  286.     strcpy(*lhs,rhs);
  287.     return SUCCESS;
  288. }
  289.  
  290. /* union together two arrays, ending up with unique array (b) */
  291. static void
  292. union_arrays(a,b,acount,bcount)
  293. int *a, *b;
  294. int acount, *bcount;
  295. {
  296.     int i, j;
  297.  
  298.     for (i=0; i < acount ;i++) {
  299.         /* check this one against all so far */
  300.         for (j=0;j < *bcount;j++) {
  301.             if (a[i] == b[j]) break;
  302.         }
  303.         /* if not found, add to array */
  304.         if (j== *bcount) {
  305.             b[j] = a[i];
  306.             (*bcount)++;
  307.         }
  308.     }
  309. }
  310.  
  311. /* return TRUE if string appears to be a set of arguments
  312.    The intent of this test is to support the ability of commands to have
  313.    all their args braced as one.  This conflicts with the possibility of
  314.    actually intending to have a single argument.
  315.    The bad case is in expect which can have a single argument with embedded
  316.    \n's although it's rare.  Examples that this code should handle:
  317.    \n        FALSE (pattern)
  318.    \n\n        FALSE
  319.    \n  \n \n    FALSE
  320.    foo        FALSE
  321.    foo\n    FALSE
  322.    \nfoo\n    TRUE  (set of args)
  323.    \nfoo\nbar    TRUE
  324.  
  325.    Current test is very cheap and almost always right :-)
  326. */
  327. int 
  328. exp_one_arg_braced(p)
  329. char *p;
  330. {
  331.     int seen_nl = FALSE;
  332.  
  333.     for (;*p;p++) {
  334.         if (*p == '\n') {
  335.             seen_nl = TRUE;
  336.             continue;
  337.         }
  338.  
  339.         if (!isspace(*p)) {
  340.             return(seen_nl);
  341.         }
  342.     }
  343.     return FALSE;
  344. }
  345.  
  346.  
  347.  
  348. /* called to execute a command of only one argument - a hack to commands */
  349. /* to be called with all args surrounded by an outer set of braces */
  350. /* returns TCL_whatever */
  351. /*ARGSUSED*/
  352. int
  353. exp_eval_with_one_arg(clientData,interp,argc,argv)
  354. ClientData clientData;
  355. Tcl_Interp *interp;
  356. int argc;
  357. char **argv;
  358. {
  359.     char *buf;
  360.     int rc;
  361.     char *a;
  362.  
  363.     /* + 2 is for blank separating cmd and null at end */
  364.     if (!(buf = malloc(strlen(argv[0]) + strlen(argv[1]) + 2))) {
  365.         exp_error(interp,"%s: no space to save arguments",argv[0]);
  366.         return(TCL_ERROR);
  367.     }
  368.     /* replace top-level newlines with blanks */
  369.     for (a=argv[1];*a;) {
  370.         extern char *TclWordEnd();
  371.  
  372.         for (;isspace(*a);a++) {
  373.             if (*a == '\n') *a = ' ';
  374.         }
  375.         a = TclWordEnd(a,0)+1;
  376.     }
  377.  
  378.     /* recreate statement */
  379.     sprintf(buf,"%s %s",argv[0],argv[1]);
  380.  
  381.     rc = Tcl_Eval(interp,buf,0,(char **)NULL);
  382.     free(buf);
  383.     return(rc);
  384.  
  385. #if 0
  386.     int i;
  387.     int len = strlen(argv[0]) + strlen(argv[1]) + 2;
  388.  
  389.     for (i=0;i<len;i++) {
  390.         if (buf[i] == '{' && just_saw_space) {
  391.             for (;i<len;i++) {
  392.                 if (buf[i] == '}') break;
  393.             }
  394.         } else if (buf[i] == '[') {
  395.             for (;i<len;i++) {
  396.                 if (buf[i] == ']') break;
  397.             }
  398.         } else if (buf[i] == '"' && just_saw_space) {
  399.             for (;i<len;i++) {
  400.                 if (buf[i] == '"') break;
  401.         } else {
  402.             if (is_space(buf[i])) {
  403.                 int just_saw_space = TRUE;
  404.                 if (buf[i] == '\n') buf[i] = ' ';
  405.             }
  406.         } else just_saw_space = FALSE;
  407.     }
  408.  
  409.  
  410.     rc = Tcl_Eval(interp,buf,0,(char **)NULL);
  411.     free(buf);
  412.     return(rc);
  413. #endif
  414. }
  415.  
  416. /* the following are just reserved addresses, to be used as ClientData */
  417. /* args to be used to tell commands how they were called. */
  418. /* The actual values won't be used, only the addresses, but I give them */
  419. /* values out of my irrational fear the compiler might collapse them all. */
  420. int expectCD_user    = 0;    /* called as expect_user */
  421. int expectCD_process    = 1;    /* called as expect */
  422. int expectCD_tty    = 2;    /* called as expect_tty */
  423.  
  424. #define EXPECT_USER    (clientData == &expectCD_user)
  425. #define EXPECT_TTY    (clientData == &expectCD_tty)
  426.  
  427. /* parse the arguments to expect or it's variants */
  428. /* returns TCL_OK or TCL_ERROR */
  429. static int
  430. parse_expect_args(clientData,interp,argc,argv,ecases,ecases_inuse,masters,mcount,me)
  431. ClientData clientData;
  432. Tcl_Interp *interp;
  433. int argc;
  434. char **argv;
  435. struct ecase **ecases;
  436. int *ecases_inuse;
  437. int **masters;        /* array of unique masters in ecases */
  438. int *mcount;        /* count of masters */
  439. int me;
  440. {
  441.     int size;
  442.     int i;
  443.     struct ecase *ec;
  444.     int m;
  445.  
  446.     int case_master;    /* master to assign to next case as it is */
  447.                 /* being parsed */
  448.  
  449.     argv++;
  450.     argc--;
  451.  
  452.     /* if we want to listen to user, use fd 0 */
  453.     if (EXPECT_USER) m = 0;    /* true if we were called as expect_user */
  454.     else if (EXPECT_TTY) m = exp_dev_tty;    /* called as expect_tty */
  455.     else {
  456.         /* it'll be checked later, if used */
  457.         (void) exp_update_master(interp,&m,0,0);
  458.     }
  459.  
  460.     *ecases_inuse = (1+argc)/2;    /* estimate of number of patterns */
  461.  
  462.     /* This takes into account optional final action */
  463.     /* If flags are used, this will be too high but it's not worth the */
  464.     /* trouble of making two passes, so we'll just adjust the count */
  465.     /* later when we find out the real amount */
  466.  
  467.     if (*ecases) free((char *)*ecases);    /* for before/after cases */
  468.     if (*ecases_inuse) {
  469.         if (0 == (*ecases = (struct ecase *)malloc(*ecases_inuse *
  470.                         sizeof(struct ecase)))) {
  471.             exp_error(interp,"malloc(%d ecases)",*ecases_inuse);
  472.             goto error;
  473.         }
  474.     } else *ecases = NULL;
  475.  
  476.     /* zero them out so that just in case we get an error in the middle */
  477.     /* of SplitList, we can deallocate them cleanly */
  478.     for (i = 0, ec = *ecases;i<argc;i+=2,ec++) {
  479.         ec->patn = 0;    /* necessary? - makes freeing code simpler? */
  480.         ec->pat = 0;
  481.         ec->body = 0;
  482.         ec->transfer = 1;
  483.         ec->re = 0;
  484.         ec->Case = CASE_NORM;
  485.         ec->owner = me;
  486.         ec->use = PAT_GLOB;
  487.     }
  488.  
  489.     /* forget old estimate of cases and prepare to calculate true number */
  490.     *ecases_inuse = 0;
  491.     ec = *ecases;
  492.     case_master = m;
  493.     for (i = 0;i<argc;i++) {
  494.         if (streq(argv[i],"-n")) {
  495.             ec->transfer = 0;
  496.             continue;
  497.         } else if (streq(argv[i],"-re")) {
  498.             ec->use = PAT_RE;
  499.             continue;
  500.         } else if (streq(argv[i],"-nocase")) {
  501.             ec->Case = CASE_LOWER;
  502.             continue;
  503.         } else if (streq(argv[i],"-i")) {
  504.             i++;
  505.             if (i>=argc) {
  506.                 exp_error(interp,"-i requires following spawn_id");
  507.                 goto error;
  508.             }
  509.             case_master = atoi(argv[i]);
  510.             continue;
  511.         }
  512.  
  513.         ec->m = case_master;
  514.  
  515.         /* save original pattern spec */
  516.         if (save_str(&ec->pat,argv[i],me)
  517.          || save_str(&ec->body,argv[i+1],me)) {
  518.             exp_error(interp,"no space to save: <%s> and <%s>",
  519.                 argv[i],argv[i+1]);
  520.             goto error;
  521.         }
  522.             
  523.         if (streq(argv[i],"timeout")) {
  524.             ec->use = PAT_TIMEOUT;
  525.         } else if (streq(argv[i],"eof")) {
  526.             ec->use = PAT_EOF;
  527.         } else if (streq(argv[i],"full_buffer")) {
  528.             ec->use = PAT_FULLBUFFER;
  529.         } else if (streq(argv[i],"default")) {
  530.             ec->use = PAT_DEFAULT;
  531.         } else if (streq(argv[i],"-brace")) {
  532.             /* allow exp_eval_with_one_arg to work */
  533.         } else if (streq(argv[i],"-dont_use")) {
  534.             if (TCL_OK != Tcl_SplitList(interp,argv[i],
  535.                         &ec->n,&ec->patn)) {
  536.                 errorlog("%s\r\n",interp->result);
  537.                 exp_error(interp,"failed to parse pattern: %s",argv[i]);
  538.                 goto error;
  539.             }
  540.         } else { /* pattern */
  541.             if (ec->use == PAT_RE) {
  542.               ec->n = 1;
  543.               tclRegexpError = 0;
  544.               if (!(ec->re = regcomp(argv[i]))) {
  545.                 exp_error(interp,"bad regular expression: %s",
  546.                             tclRegexpError);
  547.                 goto error;
  548.               }
  549.                 } else {
  550.               ec->use = PAT_GLOB;
  551.               ec->n = 1;
  552.               ec->patn = (char **)malloc(sizeof(char *));
  553.               if (!ec->patn) {
  554.                 exp_error(interp,"malloc failed while parsing pattern: %s",argv[i]);
  555.                 goto error;
  556.               }
  557.               ec->patn[0] = argv[i];
  558.             }
  559.         }
  560.         i++; ec++; (*ecases_inuse)++;
  561.     }
  562.  
  563.     /* build a list of masters for later use by ready() */
  564.     size = *ecases_inuse;
  565.     if (me == EXP_DURING) {
  566.         size += 1 + before.mcount + after.mcount;
  567.         /* "+1" just in case no patterns given, need placeholder */
  568.         /* for default pattern */
  569.     }
  570.     if (0 == (*masters = (int *)malloc(size*sizeof(int)))) {
  571.         exp_error(interp,"malloc(%d spawn_id's)",size);
  572.         goto error;
  573.     }
  574.  
  575.     *mcount = 0;    /* initially empty */
  576.     for (i=0,ec= *ecases; i < *ecases_inuse ;i++,ec++) {
  577.         int j;
  578.  
  579.         if (ec->m == SPAWN_ID_ANY) continue;
  580.  
  581.         /* check this one against all so far */
  582.         for (j=0;j < *mcount;j++) {
  583.             if (ec->m == (*masters)[j]) break;
  584.         }
  585.         /* if not found, add to array */
  586.         if (j== *mcount) {
  587.             (*masters)[j] = ec->m;
  588.             (*mcount)++;
  589.         }
  590.     }
  591.  
  592.     /* add before/after masters to candidates to pass to ready */
  593.     if (me == EXP_DURING) {
  594.         if (*mcount == 0) {
  595.             /* if no patterns given, force pattern default */
  596.             /* with current master */
  597.             (*masters)[0] = m;
  598.             (*mcount)++;
  599.         }
  600.         union_arrays(before.masters,*masters,before.mcount,mcount);
  601.         union_arrays(after.masters,*masters,after.mcount,mcount);
  602.     }
  603.  
  604.     return(TCL_OK);
  605.  
  606.  error:
  607.     if (*ecases) free_ecases(*ecases,*ecases_inuse,me);
  608.     *ecases = NULL;
  609.     *ecases_inuse = 0;
  610.     return(TCL_ERROR);
  611. }
  612.  
  613. #define EXP_IS_DEFAULT(x)    ((x) == EXP_TIMEOUT || (x) == EXP_EOF)
  614.  
  615. static char yes[] = "yes\r\n";
  616. static char no[] = "no\r\n";
  617.  
  618. struct eval_out {
  619.     struct ecase *e;        /* ecase */
  620.     struct f *f;
  621.     char *buffer;
  622.     int match;
  623. };
  624.  
  625. /* like eval_cases, but handles only a single cases that needs a real */
  626. /* string match */
  627. /* returns EXP_X where X is MATCH, NOMATCH, FULLBUFFER, TCLERRROR */
  628. static int
  629. eval_case_string(interp,e,m,o,last_f,last_case)
  630. Tcl_Interp *interp;
  631. struct ecase *e;
  632. int m;
  633. struct eval_out *o;        /* 'output' - i.e., final case of interest */
  634. /* next two args are for debugging, when they change, reprint buffer */
  635. struct f **last_f;
  636. int *last_case;
  637. {
  638.     struct f *f = fs + m;
  639.     char *buffer;
  640.  
  641.     /* if -nocase, use the lowerized buffer */
  642.     buffer = ((e->Case == CASE_NORM)?f->buffer:f->lower);
  643.  
  644.     /* if master or case changed, redisplay debug-buffer */
  645.     if ((f != *last_f) || e->Case != *last_case) {
  646.         debuglog("\r\nexpect: does {%s} (spawn_id %d) match pattern ",
  647.                 dprintify(buffer),f-fs);
  648.         *last_f = f;
  649.         *last_case = e->Case;
  650.     }
  651.  
  652.     if (e->use == PAT_RE) {
  653.         debuglog("{%s}? ",dprintify(e->pat));
  654.         tclRegexpError = 0;
  655.         if (buffer && regexec(e->re,buffer)) {
  656.             o->e = e;
  657.             o->match = e->re->endp[0]-buffer;
  658.             o->buffer = buffer;
  659.             o->f = f;
  660.             debuglog(yes);
  661.             return(EXP_MATCH);
  662.         } else {
  663.             debuglog(no);
  664.             if (tclRegexpError) {
  665.                 exp_error(interp,"r.e. match failed: %s",tclRegexpError);
  666.                 return(EXP_TCLERROR);
  667.                 }
  668.             }
  669.     } else if (e->use == PAT_GLOB) {
  670.         int j;
  671.         int match; /* # of chars that matched */
  672.  
  673.         for (j=0;j<e->n;j++) {
  674.             /* skip place-holder for spawn_id with no pattern */
  675.             if (e->patn[j][0] == '\0') continue;
  676.                 debuglog("{%s}? ",dprintify(e->patn[j]));
  677.             if (buffer && (-1 != (match = Exp_StringMatch(
  678.                     buffer,e->patn[j],&e->glob_start)))) {
  679.                 o->e = e;
  680.                 o->match = match;
  681.                 o->buffer = buffer;
  682.                 o->f = f;
  683.                 debuglog(yes);
  684.                 return(EXP_MATCH);
  685.             } else debuglog(no);
  686.         }
  687.     } else if ((f->size == f->msize) && (f->size > 0)) {
  688.         debuglog("%s? ",e->pat);
  689.         o->e = e;
  690.         o->match = f->umsize;
  691.         o->buffer = f->buffer;
  692.         o->f = f;
  693.         return(EXP_FULLBUFFER);
  694.     }
  695.     return(EXP_NOMATCH);
  696. }
  697.  
  698. /* sets o.e if successfully finds a matching pattern, eof, timeout or deflt */
  699. /* returns original status arg or EXP_TCLERROR */
  700. static int
  701. eval_cases(interp,ecs_in,ecases_inuse,m,o,last_f,last_case,status,masters,mcount)
  702. Tcl_Interp *interp;
  703. struct ecase *ecs_in;
  704. int ecases_inuse;
  705. int m;
  706. struct eval_out *o;        /* 'output' - i.e., final case of interest */
  707. /* next two args are for debugging, when they change, reprint buffer */
  708. struct f **last_f;
  709. int *last_case;
  710. int status;
  711. int *masters;
  712. int mcount;
  713. {
  714.     int i;
  715.     struct ecase *e;
  716.  
  717.     if (o->e || status == EXP_TCLERROR) return(status);
  718.  
  719.     if (status == EXP_TIMEOUT) {
  720.         for (i=0, e=ecs_in;i<ecases_inuse;i++,e++) {
  721.             if (e->use == PAT_TIMEOUT || e->use == PAT_DEFAULT) {
  722.                 o->e = e;
  723.                 break;
  724.             }
  725.         }
  726.         return(status);
  727.     } else if (status == EXP_EOF) {
  728.         for (i=0, e=ecs_in;i<ecases_inuse;i++,e++) {
  729.             if (e->use == PAT_EOF || e->use == PAT_DEFAULT) {
  730.                 if (e->m == SPAWN_ID_ANY || e->m == m) {
  731.                     o->e = e;
  732.                     break;
  733.                 }
  734.             }
  735.         }
  736.         return(status);
  737.     }
  738.  
  739.     /* the top loops are split from the bottom loop only because I can't */
  740.     /* split'em further. */
  741.  
  742.     /* The bufferful condition does not prevent a pattern match from */
  743.     /* occurring and vice versa, so it is scanned with patterns */
  744.     for (i=0, e=ecs_in;i<ecases_inuse;i++,e++) {
  745.         int j;
  746.  
  747.         if (e->use == PAT_TIMEOUT ||
  748.             e->use == PAT_DEFAULT ||
  749.             e->use == PAT_EOF) continue;
  750.  
  751. #if 0
  752.         /* if m == SPAWN_ID_ANY, then we have not yet read from any */
  753.         /* master, so check every case against its master */
  754. #endif
  755.  
  756.         /* if e->m == SPAWN_ID_ANY, then user is explicitly asking */
  757.         /* every case to be checked against every master */
  758.         if (e->m == SPAWN_ID_ANY) {
  759.             /* test against each spawn_id */
  760.             for (j=0;j<mcount;j++) {
  761.                 status = eval_case_string(interp,e,masters[j],o,last_f,last_case);
  762.                 if (status != EXP_NOMATCH) return(status);
  763.             }
  764. #if 0
  765.         } else if (m == SPAWN_ID_ANY) {
  766.             /* test against its own spawn_id */
  767.             status = eval_case_string(interp,e,e->m,o,last_f,last_case);
  768.             if (status != EXP_NOMATCH) return(status);
  769. #endif
  770.         } else {
  771.             /* reject things immediately from wrong spawn_id */
  772.             if (e->m != m) continue;
  773.  
  774.             status = eval_case_string(interp,e,m,o,last_f,last_case);
  775.             if (status != EXP_NOMATCH) return(status);
  776.         }
  777.     }
  778.     return(EXP_NOMATCH);
  779. }
  780.  
  781. /* This function handles the work of Expect_Before and After depending */
  782. /* upon the first argument */
  783. /*ARGSUSED*/
  784. int
  785. cmdExpectGlobal(clientData, interp, argc, argv)
  786. ClientData clientData;
  787. Tcl_Interp *interp;
  788. int argc;
  789. char **argv;
  790. {
  791.     struct expect_special *e;
  792.  
  793.     if (argc == 2 && strchr(argv[1],'\n')) {
  794.         return(exp_eval_with_one_arg(clientData,interp,argc,argv));
  795.     }
  796.  
  797.     e = (struct expect_special *) clientData;
  798.     return(parse_expect_args(clientData,interp,argc,argv,&e->ecases,
  799.         &e->ecount,&e->masters,&e->mcount,e->me));
  800. }
  801.  
  802. /* adjusts file according to user's size request */
  803. /* return TCL_ERROR or TCL_OK */
  804. int
  805. exp_adjust(interp,f)
  806. Tcl_Interp *interp;
  807. struct f *f;
  808. {
  809.     int new_msize;
  810.     char *new_buf;
  811.  
  812.     /* get the latest buffer size.  Double the user input for */
  813.     /* two reasons.  1) Need twice the space in case the match */
  814.     /* straddles two bufferfuls, 2) easier to hack the division */
  815.     /* by two when shifting the buffers later on.  The extra  */
  816.     /* byte in the malloc's is just space for a null we can slam on the */
  817.     /* end.  It makes the logic easier later.  The -1 here is so that */
  818.     /* requests actually come out to even/word boundaries (if user */
  819.     /* gives "reasonable" requests) */
  820.     new_msize = f->umsize*2 - 1;
  821.     if (new_msize != f->msize) {
  822.         if (!f->buffer) {
  823.             /* allocate buffer space for 1st time */
  824.             f->lower = malloc((unsigned)new_msize+1);
  825.             f->buffer = malloc((unsigned)new_msize+1);
  826.             if ((!f->buffer) && (!f->lower)) {
  827.                 exp_error(interp,"out of space - failed to malloc initial match buffer");
  828.                 if (f->lower) {free(f->lower); f->lower = 0;}
  829.                 return(TCL_ERROR);
  830.             }
  831.             f->size = 0;
  832.         } else {
  833.             /* buffer already exists - resize */
  834.             if (0 == (new_buf = realloc(f->buffer,new_msize+1))) {
  835.                 exp_error(interp,"failed to grow match buf to %d bytes",f->umsize);
  836.                 return(TCL_ERROR);
  837.             }
  838.             f->buffer = new_buf;
  839.             if (0 == (new_buf = realloc(f->lower,new_msize+1))) {
  840.                 exp_error(interp,"failed to grow match buf to %d bytes",f->umsize);
  841.                 /* no need to free other buffer */
  842.                 /* - code will still work even if */
  843.                 /* buffer is larger than necessary */
  844.                 return(TCL_ERROR);
  845.             }
  846.             f->lower = new_buf;
  847.             /* if truncated, forget about some data */
  848.             if (f->size >= f->msize) f->size = f->msize-1;
  849.         }
  850.         f->msize = new_msize;
  851.         f->buffer[f->size] = '\0';
  852.     }
  853.     return(TCL_OK);
  854. }
  855.  
  856.  
  857. /*
  858.  
  859.  expect_read() does the logical equivalent of a read() for the
  860. expect command.  This includes figuring out which descriptor should
  861. be read from.
  862.  
  863. The result of the read() is left in a spawn_id's buffer rather than
  864. explicitly passing it back.  Note that if someone else has modified a
  865. buffer either before or while this expect is running (i.e., if we or
  866. some event has called Tcl_Eval which did another expect/interact),
  867. expect_read will also call this a successful read (for the purposes if
  868. needing to pattern match against it).
  869.  
  870. */
  871. /* if it returns a negative number, it corresponds to a EXP_XXX result */
  872. /* if it returns a non-negative number, it means there is data */
  873. /* (0 means nothing new was actually read, but it should be looked at again) */
  874. int
  875. expect_read(interp,masters,masters_max,m,timeout,key)
  876. Tcl_Interp *interp;
  877. int *masters;
  878. int masters_max;
  879. int *m;                /* new master */
  880. int timeout;
  881. int key;
  882. {
  883.     struct f *f;
  884.     int cc;
  885.     int write_count;
  886.  
  887.     cc = exp_get_next_event(interp,masters,masters_max,m,timeout,key);
  888.  
  889.     if (cc == EXP_DATA_NEW) {
  890.         /* try to read it */
  891.  
  892.         cc = i_read(*m,timeout);
  893.  
  894.         /* the meaning of 0 from i_read means eof.  Muck with it a */
  895.         /* little, so that from now on it means "no new data arrived */
  896.         /* but it should be looked at again anyway". */
  897.         if (cc == 0) {
  898.             cc = EXP_EOF;
  899.         } else if (cc > 0) {
  900.             f = fs + *m;
  901.             f->buffer[f->size += cc] = '\0';
  902.  
  903.             /* strip parity if requested */
  904.             if (f->parity == 0) {
  905.                 /* do it from end backwards */
  906.                 char *p = f->buffer + f->size - 1;
  907.                 int count = cc;
  908.                 while (count--) {
  909.                     *p-- &= 0x7f;
  910.                 }
  911.         }
  912.         }
  913.     } else if (cc == EXP_DATA_OLD) {
  914.         f = fs + *m;
  915.         cc = 0;
  916.     }
  917.  
  918.     if (cc == EXP_ABEOF) {    /* abnormal EOF */
  919.         /* On many systems, ptys produce EIO upon EOF - sigh */
  920.         if (i_read_errno == EIO) {
  921.             /* Sun, Cray, BSD, and others */
  922.             cc = EXP_EOF;
  923.         } else {
  924.             if (i_read_errno == EBADF) {
  925.                 exp_error(interp,"bad spawn_id (process died earlier?)");
  926.             } else {
  927.                 exp_error(interp,"i_read(spawn_id=%d): %s",
  928.                     m,sys_errlist[errno]);
  929.                 exp_close(interp,*m);
  930.             }
  931.             return(EXP_TCLERROR);
  932.             /* was goto error; */
  933.         }
  934.     }
  935.  
  936.     /* EOF and TIMEOUT return here */
  937.     /* In such cases, there is no need to update screen since, if there */
  938.     /* was prior data read, it would have been sent to the screen when */
  939.     /* it was read. */
  940.     if (cc < 0) return (cc);
  941.  
  942.     /* update display */
  943.  
  944.     if (f->size) write_count = f->size - f->printed;
  945.     else write_count = 0;
  946.  
  947.     if (write_count) {
  948.         if (logfile_all || (loguser && logfile)) {
  949.             fwrite(f->buffer + f->printed,1,write_count,logfile);
  950.         }
  951.         /* don't write to user if they're seeing it already, */
  952.         /* that is, typing it! */
  953.         if (loguser && !f_is_user(f)) fwrite(f->buffer + f->printed,
  954.                     1,write_count,stdout);
  955.         if (debugfile) fwrite(f->buffer + f->printed,
  956.                     1,write_count,debugfile);
  957.  
  958.         /* remove nulls from input, since there is no way */
  959.         /* for Tcl to deal with such strings.  Doing it here */
  960.         /* lets them be sent to the screen, just in case */
  961.         /* they are involved in formatting operations */
  962.         f->size -= rm_nulls(f->buffer + f->printed,write_count);
  963.         f->buffer[f->size] = '\0';
  964.  
  965.         /* copy to lowercase buffer */
  966.         exp_lowmemcpy(f->lower+f->printed,
  967.                   f->buffer+f->printed,
  968.                     1 + f->size - f->printed);
  969.  
  970.         f->printed = f->size; /* count'm even if not logging */
  971.     }
  972.     return(cc);
  973. }
  974.  
  975. /* this should really be local to i_read, however the longjmp could then */
  976. /* clobber them */
  977. static int i_read_cc;
  978.  
  979. /* returns # of chars read or (non-positive) error of form EXP_XXX */
  980. /* returns 0 for end of file */
  981. /* If timeout is non-zero, set an alarm before doing the read, else assume */
  982. /* the read will complete immediately. */
  983. /*ARGSUSED*/
  984. int
  985. i_read(m,timeout)
  986. int m;
  987. int timeout;
  988. {
  989.     struct f *f;
  990.     i_read_cc = EXP_TIMEOUT;
  991.  
  992.     if (1 != setjmp(env)) {
  993.         env_valid = TRUE;
  994.  
  995.         f = fs + m;
  996.  
  997.         /* when buffer fills, copy second half over first and */
  998.         /* continue, so we can do matches over multiple buffers */
  999.         if (f->size == f->msize) {
  1000.             int half = f->size/2;
  1001.             memcpy(f->buffer,f->buffer+half,half);
  1002.             memcpy(f->lower, f->lower +half,half);
  1003.             f->size = half;
  1004.             f->printed -= half;
  1005.             if (f->printed < 0) f->printed = 0;
  1006.         }
  1007.  
  1008. #if SIMPLE_EVENT
  1009.         alarm((timeout > 0)?timeout:1);
  1010. #endif
  1011.  
  1012. #if MAJOR_DEBUGGING
  1013. debuglog("read(fd=%d,buffer=%x,length=%d)",
  1014. *m,f->buffer+f->size, f->msize-f->size);
  1015. #endif
  1016.         i_read_cc = read(m,f->buffer+f->size, f->msize-f->size);
  1017. #if MAJOR_DEBUGGING
  1018. debuglog("= %d\r\n",i_read_cc);
  1019. #endif
  1020.         i_read_errno = errno;    /* errno can be overwritten by the */
  1021.                     /* time we return */
  1022. #if SIMPLE_EVENT
  1023.         alarm(0);
  1024. #endif
  1025.     }
  1026.     /* setjmp returned, which means alarm went off or ^C pressed */
  1027.     env_valid = FALSE;
  1028.     return(i_read_cc);
  1029. }
  1030.  
  1031. /* variables predefined by expect are retrieved using this routine
  1032. which looks in the global space if they are not in the local space.
  1033. This allows the user to localize them if desired, and also to
  1034. avoid having to put "global" in procedure definitions.
  1035. */
  1036. char *
  1037. exp_get_var(interp,var)
  1038. Tcl_Interp *interp;
  1039. char *var;
  1040. {
  1041.     char *val;
  1042.  
  1043.     if (NULL != (val = Tcl_GetVar(interp,var,0 /* local */)))
  1044.         return(val);
  1045.     return(Tcl_GetVar(interp,var,TCL_GLOBAL_ONLY));
  1046. }
  1047.  
  1048. static int
  1049. get_timeout(interp)
  1050. Tcl_Interp *interp;
  1051. {
  1052.     char *t;
  1053.  
  1054.     if (NULL != (t = get_var(EXPECT_TIMEOUT))) timeout = atoi(t);
  1055.     return(timeout);
  1056. }
  1057.  
  1058. #if 0
  1059. /* unfinished_thoughts_on_SIGWINCH */
  1060. #if defined(SIGWINCH) && defined(TIOCGWINSZ)
  1061. static void
  1062. sigwinch_handler()
  1063. {
  1064. #if 0
  1065.     signal(SIGWINCH,sinwinch_handler);
  1066. #endif
  1067.     ioctl(exp_dev_tty,TIOCSWINSZ,);
  1068. }
  1069. #endif
  1070. #endif /*0*/
  1071.  
  1072. #if 0
  1073. #ifndef _TK
  1074. #define arm_event_handlers(x,y)
  1075. #define disarm_event_handlers(x,y)
  1076. #else
  1077. define arm_event_handlers exp_arm_event_handlers
  1078. define disarm_event_handlers exp_disarm_event_handlers
  1079. void exp_arm_event_handlers();
  1080. void exp_disarm_event_handlers();
  1081. #endif
  1082. #endif
  1083.  
  1084. /*ARGSUSED*/
  1085. int
  1086. cmdExpect(clientData, interp, argc, argv)
  1087. ClientData clientData;
  1088. Tcl_Interp *interp;
  1089. int argc;
  1090. char **argv;
  1091. {
  1092.     int cc;            /* number of chars returned in a single read */
  1093.                 /* or negative EXP_whatever */
  1094.     int m;            /* before doing an actual read, attempt */
  1095.                 /* to match upon any spawn_id */
  1096.     struct f *f;        /* file associated with master */
  1097.  
  1098.     int i;            /* trusty temporary */
  1099.     struct ecase *ecases;
  1100.     int ecases_inuse;    /* number of ecases to use */
  1101.     int *masters;        /* array of masters to watch */
  1102.     int mcount;        /* number of masters to watch */
  1103.  
  1104.     struct eval_out eo;    /* final case of interest */
  1105.  
  1106.     int result;        /* Tcl result */
  1107.  
  1108.     time_t start_time_total;/* time at beginning of this procedure */
  1109.     time_t start_time = 0;    /* time when restart label hit */
  1110.     time_t current_time = 0;/* current time (when we last looked)*/
  1111.     time_t end_time;    /* future time at which to give up */
  1112.     time_t elapsed_time_total;/* time from now to match/fail/timeout */
  1113.     time_t elapsed_time;    /* time from restart to (ditto) */
  1114.  
  1115.     struct f *last_f;    /* for differentiating when multiple f's */
  1116.                 /* to print out better debugging messages */
  1117.     int last_case;        /* as above but for case */
  1118.     int first_time = 1;    /* if not "restarted" */
  1119.  
  1120.     int key;        /* identify this expect command instance */
  1121.  
  1122.     int remtime;        /* remaining time in timeout */
  1123.  
  1124.     if ((argc == 2) && exp_one_arg_braced(argv[1])) {
  1125.         return(exp_eval_with_one_arg(clientData,interp,argc,argv));
  1126.     }
  1127.  
  1128.     time(&start_time_total);
  1129.     start_time = start_time_total;
  1130.  restart:
  1131.     if (first_time) first_time = 0;
  1132.     else time(&start_time);
  1133.  
  1134.     key = expect_key++;
  1135.  
  1136.     cc = EXP_NOMATCH;
  1137. #if 0
  1138.     m = SPAWN_ID_ANY;
  1139. #endif
  1140.     ecases = 0;
  1141.     masters = 0;
  1142.     mcount = 0;
  1143.     result = TCL_OK;
  1144.     last_f = 0;
  1145.     /* end of restart code */
  1146.  
  1147.     eo.e = 0;        /* no final case yet */
  1148.     eo.f = 0;        /* no final file selected yet */
  1149.     eo.match = 0;        /* nothing matched yet */
  1150.  
  1151.     /* get the latest timeout */
  1152.     (void) get_timeout(interp);
  1153.  
  1154.     /* make arg list for processing cases */
  1155.     /* do it dynamically, since expect can be called recursively */
  1156.     if (TCL_ERROR == parse_expect_args(clientData,interp,argc,argv,
  1157.             &ecases,&ecases_inuse,
  1158.             &masters,&mcount,
  1159.             EXP_DURING)) return(TCL_ERROR);
  1160.  
  1161.     for (i=0;i<mcount;i++) {
  1162.         /* validate all input descriptors */
  1163.         if (!(f = exp_fd2f(interp,masters[i],1,1,"expect"))) {
  1164.             result = TCL_ERROR;
  1165.             goto cleanup;
  1166.         }
  1167.     }
  1168.  
  1169.     /* timeout code is a little tricky, be very careful changing it */
  1170.     if (timeout != EXP_TIME_INFINITY) {
  1171.         time(¤t_time);
  1172.         end_time = current_time + timeout;
  1173.     }
  1174.  
  1175.     /* remtime and current_time updated at bottom of loop */
  1176.     remtime = timeout;
  1177.  
  1178.     for (;;) {
  1179.         if ((timeout != EXP_TIME_INFINITY) && (remtime < 0)) {
  1180.             cc = EXP_TIMEOUT;
  1181.         } else {
  1182.             cc = expect_read(interp,masters,mcount,&m,remtime,key);
  1183.         }
  1184.  
  1185.         /*SUPPRESS 530*/
  1186.         if (cc == EXP_EOF) {
  1187.             /* do nothing */
  1188.         } else if (cc == EXP_TIMEOUT) {
  1189.             debuglog("expect: timed out\r\n");
  1190.         } else if (cc == EXP_TCLERROR) {
  1191.             goto error;
  1192.         } else {
  1193.             /* new data if cc > 0, same old data if cc == 0 */
  1194.  
  1195.             f = fs + m;
  1196.  
  1197.             /* below here, cc as general status */
  1198.             cc = EXP_NOMATCH;
  1199.  
  1200.             /* force redisplay of buffer when debugging */
  1201.             last_f = 0;
  1202.         }
  1203.  
  1204.         cc = eval_cases(interp,before.ecases,before.ecount,
  1205.             m,&eo,&last_f,&last_case,cc,masters,mcount);
  1206.         cc = eval_cases(interp,ecases,ecases_inuse,
  1207.             m,&eo,&last_f,&last_case,cc,masters,mcount);
  1208.         cc = eval_cases(interp,after.ecases,after.ecount,
  1209.             m,&eo,&last_f,&last_case,cc,masters,mcount);
  1210.         if (cc == EXP_TCLERROR) goto error;
  1211.         /* special eof code that cannot be done in eval_cases */
  1212.         /* or above, because it would then be executed several times */
  1213.         if (cc == EXP_EOF) {
  1214.             eo.f = fs + m;
  1215.             eo.match = eo.f->size;
  1216.             eo.buffer = eo.f->buffer;
  1217.             debuglog("expect: read eof\r\n");
  1218.             break;
  1219.         } else if (cc == EXP_TIMEOUT) break;
  1220.         /* break if timeout or eof and failed to find a case for it */
  1221.  
  1222.         if (eo.e) break;
  1223.  
  1224.         /* no match was made with current data, force a read */
  1225.         f->force_read = TRUE;
  1226. #if 0
  1227.         /* if we've not yet actually read anything, don't update */
  1228.         /* time forcing at least one read to be done if timeout > 0 */
  1229.     if (m != SPAWN_ID_ANY)
  1230. #endif
  1231.         if (timeout != EXP_TIME_INFINITY) {
  1232.             time(¤t_time);
  1233.             remtime = end_time - current_time;
  1234.         }
  1235.     }
  1236.  
  1237.     goto done;
  1238.  
  1239. error:
  1240.     result = TCL_ERROR;
  1241.  done:
  1242. #define out(i,val)  debuglog("expect: set %s(%s) {%s}\r\n",EXPECT_OUT,i, \
  1243.                         dprintify(val)); \
  1244.             if (!Tcl_SetVar2(interp,EXPECT_OUT,i,val,0)) \
  1245.                 {result = TCL_ERROR; goto cleanup;}
  1246.     {
  1247.         char value[20];
  1248.  
  1249.         time(¤t_time);
  1250.         elapsed_time = current_time - start_time;
  1251.         elapsed_time_total = current_time - start_time_total;
  1252.         sprintf(value,"%d",elapsed_time);
  1253.         out("seconds",value);
  1254.         sprintf(value,"%d",elapsed_time_total);
  1255.         out("seconds_total",value);
  1256.     }
  1257.  
  1258.     if (result != TCL_ERROR) {
  1259.         char *body = 0;
  1260.         char *buffer;    /* pointer to normal or lowercased data */
  1261.         struct ecase *e = 0;    /* points to current ecase */
  1262.         int match = -1;        /* characters matched */
  1263.         char match_char;    /* place to hold char temporarily */
  1264.                     /* uprooted by a NULL */
  1265.  
  1266.         if (eo.e) {
  1267.             e = eo.e;
  1268.             body = e->body;
  1269.             if (cc != EXP_TIMEOUT) {
  1270. /*            if (e->use != PAT_TIMEOUT) {*/
  1271.                 f = eo.f;
  1272.                 match = eo.match;
  1273.                 buffer = eo.buffer;
  1274.             }
  1275.         } else if (cc == EXP_EOF) {
  1276.             /* read an eof but no user-supplied case */
  1277.             f = eo.f;
  1278.             match = eo.match;
  1279.             buffer = eo.buffer;
  1280.         }            
  1281.  
  1282.         if (match >= 0) {
  1283.             char name[20], value[20];
  1284.  
  1285.             if (e && e->use == PAT_RE) {
  1286.                 for (i=0;i<NSUBEXP;i++) {
  1287.                     int offset;
  1288.  
  1289.                     if (e->re->startp[i] == 0) break;
  1290.  
  1291.                     /* start index */
  1292.                     sprintf(name,"%d,start",i);
  1293.                     offset = e->re->startp[i]-buffer;
  1294.                     sprintf(value,"%d",offset);
  1295.                     out(name,value);
  1296.  
  1297.                     /* end index */
  1298.                     sprintf(name,"%d,end",i);
  1299.                     sprintf(value,"%d",
  1300.                         e->re->endp[i]-buffer-1);
  1301.                     out(name,value);
  1302.  
  1303.                     /* string itself */
  1304.                     sprintf(name,"%d,string",i);
  1305. #if 0
  1306.     /* doesn't seem to be used? */
  1307.                     str = f->buffer + offset;*/
  1308. #endif
  1309.                     /* temporarily null-terminate in */
  1310.                     /* middle */
  1311.                     match_char = *e->re->endp[i];
  1312.                     *e->re->endp[i] = 0;
  1313.                     out(name,e->re->startp[i]);
  1314.                     *e->re->endp[i] = match_char;
  1315.                 }
  1316.                 /* redefine length of string that */
  1317.                 /* matched for later extraction */
  1318.                 match = e->re->endp[0]-buffer;
  1319.             } else if (e && e->use == PAT_GLOB) {
  1320.                 char *str;
  1321.  
  1322.                 /* start index */
  1323.                 sprintf(value,"%d",e->glob_start);
  1324.                 out("0,start",value);
  1325.  
  1326.                 /* end index */
  1327.                 sprintf(value,"%d",e->glob_start + match - 1);
  1328.                 out("0,end",value);
  1329.  
  1330.                 /* string itself */
  1331.                 str = f->buffer + e->glob_start;
  1332.                 /* temporarily null-terminate in middle */
  1333.                 match_char = str[match];
  1334.                 str[match] = 0;
  1335.                 out("0,string",str);
  1336.                 str[match] = match_char;
  1337.  
  1338.                 /* redefine length of string that */
  1339.                 /* matched for later extraction */
  1340.                 match += e->glob_start;
  1341.             } else if (e && e->use == PAT_FULLBUFFER) {
  1342.                 debuglog("expect: full buffer\r\n");
  1343.             }
  1344.         }
  1345.  
  1346.         /* this is broken out of (match > 0) (above) since it can */
  1347.         /* that an EOF occurred with match == 0 */
  1348.         if (eo.f) {
  1349.             char spawn_id[10];    /* enough for a %d */
  1350.  
  1351.             sprintf(spawn_id,"%d",f-fs);
  1352.             out("spawn_id",spawn_id);
  1353.  
  1354.             /* save buf[0..match] */
  1355.             /* temporarily null-terminate string in middle */
  1356.             match_char = f->buffer[match];
  1357.             f->buffer[match] = 0;
  1358.             out("buffer",f->buffer);
  1359.             /* remove middle-null-terminator */
  1360.             f->buffer[match] = match_char;
  1361.  
  1362.             /* "!e" means no case matched - transfer by default */
  1363.             if (!e || e->transfer) {
  1364.                 /* delete matched chars from input buffer */
  1365.                 f->size -= match;
  1366.                 f->printed -= match;
  1367.                 if (f->size != 0) {
  1368.                    memcpy(f->buffer,f->buffer+match,f->size);
  1369.                    memcpy(f->lower,f->lower+match,f->size);
  1370.                 }
  1371.                 f->buffer[f->size] = '\0';
  1372.                 f->lower[f->size] = '\0';
  1373.             }
  1374.  
  1375.             if (cc == EXP_EOF) exp_close(interp,f - fs);
  1376.  
  1377.         }
  1378.  
  1379.         if (body) {
  1380.             result = Tcl_Eval(interp,body,0,(char **) NULL);
  1381.         }
  1382.     }
  1383.  
  1384.  cleanup:
  1385.     free_ecases(ecases,ecases_inuse,EXP_DURING);
  1386.     if (masters) free((char *)masters);
  1387.  
  1388.     if (result == TCL_CONTINUE_EXPECT) {
  1389.         debuglog("expect: continuing expect\r\n");
  1390.         goto restart;
  1391.     }
  1392.  
  1393.     return(result);
  1394. }
  1395.  
  1396. /* lowmemcpy - like memcpy but it lowercases result */
  1397. void
  1398. exp_lowmemcpy(dest,src,n)
  1399. char *dest;
  1400. char *src;
  1401. int n;
  1402. {
  1403.     for (;n>0;n--) {
  1404.         *dest = ((isascii(*src) && isupper(*src))?tolower(*src):*src);
  1405.         src++;    dest++;
  1406.     }
  1407. }
  1408.  
  1409. /* The following functions implement expect's glob-style string matching */
  1410. /* Exp_StringMatch allow's implements the unanchored front (or conversely */
  1411. /* the '^') feature.  Exp_StringMatch2 does the rest of the work. */
  1412. int    /* returns # of chars that matched */
  1413. Exp_StringMatch(string, pattern,offset)
  1414. char *string;
  1415. char *pattern;
  1416. int *offset;    /* offset from beginning of string where pattern matches */
  1417. {
  1418.     char *s;
  1419.     int sm;    /* count of chars matched or -1 */
  1420.     int caret = FALSE;
  1421.  
  1422.     *offset = 0;
  1423.  
  1424.     if (pattern[0] == '^') {
  1425.         caret = TRUE;
  1426.         pattern++;
  1427.     }
  1428.  
  1429.     sm = Exp_StringMatch2(string,pattern);
  1430.     if (sm >= 0) return(sm);
  1431.  
  1432.     if (caret) return(-1);
  1433.  
  1434.     if (pattern[0] == '*') return(-1);
  1435.  
  1436.     for (s = string;*s;s++) {
  1437.          sm = Exp_StringMatch2(s,pattern);
  1438.         if (sm != -1) {
  1439.             *offset = s-string;
  1440.             return(sm);
  1441.         }
  1442.     }
  1443.     return(-1);
  1444. }
  1445.  
  1446. /* Exp_StringMatch2 --
  1447.  
  1448. Like Tcl_StringMatch except that
  1449. 1) returns number of characters matched, -1 if failed.
  1450.     (Can return 0 on patterns like "" or "$")
  1451. 2) does not require pattern to match to end of string
  1452. 3) Original code is stolen from Tcl_StringMatch
  1453. */
  1454.  
  1455. int Exp_StringMatch2(string,pattern)
  1456.     register char *string;    /* String. */
  1457.     register char *pattern;    /* Pattern, which may contain
  1458.                  * special characters. */
  1459. {
  1460.     char c2;
  1461.     int match = 0;    /* # of chars matched */
  1462.  
  1463.     while (1) {
  1464.     /* See if we're at the end of both the pattern and the string.
  1465.      * If so, we succeeded.  If we're at the end of the pattern
  1466.      * but not at the end of the string, we failed.
  1467.      */
  1468.     
  1469.     if (*pattern == 0) {
  1470.         /* removed test for end of string - DEL */
  1471.         return match;
  1472.     }
  1473.  
  1474.     if ((*string == 0) && (*pattern != '*')) {
  1475.         return -1;
  1476.     }
  1477.  
  1478.     /* Check for a "*" as the next pattern character.  It matches
  1479.      * any substring.  We handle this by calling ourselves
  1480.      * recursively for each postfix of string, until either we
  1481.      * match or we reach the end of the string.
  1482.      */
  1483.     
  1484.     if (*pattern == '*') {
  1485.         pattern += 1;
  1486.         if (*pattern == 0) {
  1487.         return(strlen(string)+match); /* DEL */
  1488.         }
  1489.         while (*string != 0) {
  1490.         int rc;                    /* DEL */
  1491.  
  1492.         if (-1 != (rc = Exp_StringMatch2(string, pattern))) {
  1493.             return rc+match;        /* DEL */
  1494.         }
  1495.         string += 1;
  1496.         match++;                /* DEL */
  1497.         }
  1498.         if (*pattern == '$') return 0;    /* handle *$ */
  1499.         return -1;                    /* DEL */
  1500.     }
  1501.     
  1502.     /* Check for a "?" as the next pattern character.  It matches
  1503.      * any single character.
  1504.      */
  1505.  
  1506.     if (*pattern == '?') {
  1507.         goto thisCharOK;
  1508.     }
  1509.  
  1510.     /* Check for a "[" as the next pattern character.  It is followed
  1511.      * by a list of characters that are acceptable, or by a range
  1512.      * (two characters separated by "-").
  1513.      */
  1514.     
  1515.     if (*pattern == '[') {
  1516.         pattern += 1;
  1517.         while (1) {
  1518.         if ((*pattern == ']') || (*pattern == 0)) {
  1519.             return 0;
  1520.         }
  1521.         if (*pattern == *string) {
  1522.             break;
  1523.         }
  1524.         if (pattern[1] == '-') {
  1525.             c2 = pattern[2];
  1526.             if (c2 == 0) {
  1527.             return -1;        /* DEL */
  1528.             }
  1529.             if ((*pattern <= *string) && (c2 >= *string)) {
  1530.             break;
  1531.             }
  1532.             if ((*pattern >= *string) && (c2 <= *string)) {
  1533.             break;
  1534.             }
  1535.             pattern += 2;
  1536.         }
  1537.         pattern += 1;
  1538.         }
  1539.         while ((*pattern != ']') && (*pattern != 0)) {
  1540.         pattern += 1;
  1541.         }
  1542.         goto thisCharOK;
  1543.     }
  1544.     
  1545.     /* If the last pattern character is '$', verify that the entire
  1546.      * string has been matched. - DEL 
  1547.      */
  1548.  
  1549.     if ((*pattern == '$') && (pattern[1] == 0)) {
  1550.         if (*string == 0) return(0);
  1551.         else return(-1);        
  1552.     }
  1553.  
  1554.     /* If the next pattern character is '/', just strip off the '/'
  1555.      * so we do exact matching on the character that follows.
  1556.      */
  1557.     
  1558.     if (*pattern == '\\') {
  1559.         pattern += 1;
  1560.         if (*pattern == 0) {
  1561.         return -1;
  1562.         }
  1563.     }
  1564.  
  1565.     /* There's no special character.  Just make sure that the next
  1566.      * characters of each string match.
  1567.      */
  1568.     
  1569.     if (*pattern != *string) {
  1570.         return -1;
  1571.     }
  1572.  
  1573.     thisCharOK: pattern += 1;
  1574.     string += 1;
  1575.     match++;
  1576.     }
  1577. }
  1578.  
  1579.  
  1580. /* Tcl statements to execute upon various signals */
  1581. /* Each is handled by the same "generic_sighandler (below)" which */
  1582. /* looks them up here */
  1583. static struct {    /* one per signal */
  1584.     char *action;        /* Tcl command to execute upon sig */
  1585.     char *name;        /* name of C macro */
  1586.     Tcl_Interp *interp;
  1587. } signals[NSIG];
  1588.  
  1589. void
  1590. exp_init_trap()
  1591. {
  1592.     int i;
  1593.  
  1594.     for (i=0;i<NSIG;i++) {
  1595.         signals[i].name = 0;
  1596.         signals[i].action = 0;
  1597.     }
  1598.  
  1599.     /* defined by C standard */
  1600. #if defined(SIGABRT)
  1601.     /* unbelievable but some systems don't support this (e.g. SunOS 3.5) */
  1602.     signals[SIGABRT].name = "SIGABRT";
  1603. #endif
  1604.     signals[SIGFPE ].name = "SIGFPE";
  1605.     signals[SIGILL ].name = "SIGILL";
  1606.     signals[SIGINT ].name = "SIGINT";
  1607.     signals[SIGSEGV].name = "SIGSEGV";
  1608.     signals[SIGTERM].name = "SIGTERM";
  1609.  
  1610.     /* our own extension */
  1611.     signals[0].name = "ONEXIT";
  1612.  
  1613.     /* nonstandard but common */
  1614. #if defined(SIGHUP)        /* hangup */
  1615.     signals[SIGHUP ].name = "SIGHUP";
  1616. #endif
  1617. #if defined(SIGQUIT)        /* quit */
  1618.     signals[SIGQUIT].name = "SIGQUIT";
  1619. #endif
  1620. #if defined(SIGTRAP)        /* trace trap (not reset when caught) */
  1621.     signals[SIGTRAP].name = "SIGTRAP";
  1622. #endif
  1623. #if defined(SIGIOT)        /* IOT instruction */
  1624.     signals[SIGIOT ].name = "SIGIOT";
  1625. #endif
  1626. #if defined(SIGEMT)        /* EMT instruction */
  1627.     signals[SIGEMT ].name = "SIGEMT";
  1628. #endif
  1629. #if defined(SIGKILL)        /* kill (cannot be caught or ignored) */
  1630.     signals[SIGKILL].name = "SIGKILL";
  1631. #endif
  1632. #if defined(SIGBUS)        /* bus error */
  1633.     signals[SIGBUS ].name = "SIGBUS";
  1634. #endif
  1635. #if defined(SIGSYS)        /* bad argument to system call */
  1636.     signals[SIGSYS ].name = "SIGSYS";
  1637. #endif
  1638. #if defined(SIGPIPE)        /* write on a pipe with no one to read it */
  1639.     signals[SIGPIPE].name = "SIGPIPE";
  1640. #endif
  1641. #if defined(SIGALRM)        /* alarm clock */
  1642.     signals[SIGALRM].name = "*SIGALRM";
  1643. #endif
  1644. #if defined(SIGCLD)        /* Like SIGCHLD.  */
  1645.     signals[SIGCLD ].name = "SIGCLD";
  1646. #endif
  1647. #if defined(SIGPWR)        /* imminent power failure */
  1648.     signals[SIGPWR ].name = "SIGPWR";
  1649. #endif
  1650. #if defined(SIGPOLL)        /* For keyboard input?  */
  1651.     signals[SIGPOLL].name = "SIGPOLL";
  1652. #endif
  1653. #if defined(SIGURG)        /* urgent condition on IO channel */
  1654.     signals[SIGURG ].name = "SIGURG";
  1655. #endif
  1656. #if defined(SIGSTOP)        /* sendable stop signal not from tty */
  1657.     signals[SIGSTOP].name = "SIGSTOP";
  1658. #endif
  1659. #if defined(SIGTSTP)        /* stop signal from tty */
  1660.     signals[SIGTSTP].name = "SIGTSTP";
  1661. #endif
  1662. #if defined(SIGCONT)        /* continue a stopped process */
  1663.     signals[SIGCONT].name = "SIGCONT";
  1664. #endif
  1665. #if defined(SIGCHLD)        /* to parent on child stop or exit */
  1666.     signals[SIGCHLD].name = "SIGCHLD";
  1667. #endif
  1668. #if defined(SIGTTIN)        /* to readers pgrp upon background tty read */
  1669.     signals[SIGTTIN].name = "SIGTTIN";
  1670. #endif
  1671. #if defined(SIGTTOU)        /* like TTIN for output if (tp->t_local<OSTOP) */
  1672.     signals[SIGTTOU].name = "SIGTTOU";
  1673. #endif
  1674. #if defined(SIGIO)        /* input/output signal */
  1675.     signals[SIGIO  ].name = "SIGIO";
  1676. #endif
  1677. #if defined(SIGXCPU)        /* exceeded CPU time limit */
  1678.     signals[SIGXCPU].name = "SIGXCPU";
  1679. #endif
  1680. #if defined (SIGXFSZ)        /* exceeded file size limit */
  1681.     signals[SIGXFSZ].name = "SIGXFSZ";
  1682. #endif
  1683. #if defined(SIGVTALRM)        /* virtual time alarm */
  1684.     signals[SIGVTALRM].name = "SIGVTALRM";
  1685. #endif
  1686. #if defined(SIGPROF)        /* profiling time alarm */
  1687.     signals[SIGPROF].name = "SIGPROF";
  1688. #endif
  1689. #if defined(SIGWINCH)        /* window changed */
  1690.     signals[SIGWINCH].name = "SIGWINCH";
  1691. #endif
  1692. #if defined(SIGLOST)        /* resource lost (eg, record-lock lost) */
  1693.     signals[SIGLOST].name = "SIGLOST";
  1694. #endif
  1695. #if defined(SIGUSR1)        /* user defined signal 1 */
  1696.     signals[SIGUSR1].name = "SIGUSR1";
  1697. #endif
  1698. #if defined(SIGUSR2)        /* user defined signal 2 */
  1699.     signals[SIGUSR2].name = "SIGUSR2";
  1700. #endif
  1701.  
  1702. #if 0
  1703. #ifdef HPUX
  1704.     /* initially forced to catch & discard SIGCLD to collect wait status */
  1705.     (void) Tcl_Eval(interp,"trap SIG_DFL SIGCHLD",0,(char **)0);
  1706.     /* no point in checking for errors here, since it is so early on */
  1707.     /* something else will be sure to fail before application begins */
  1708.  
  1709.     /* note that SIGCHLD is used rather than SIGCLD since HPUX defines */
  1710.     /* them both, but expect can only handle one, and it handles the */
  1711.     /* "wrong" one, first */
  1712. #endif
  1713. #endif
  1714. }
  1715.  
  1716. /* reserved to us if name begins with asterisk */
  1717. #define SIG_RESERVED(x)    (signals[x].name[0] == '*')
  1718.  
  1719. static char *
  1720. signal_to_string(sig)
  1721. int sig;
  1722. {
  1723.     if (sig < 0 || sig > NSIG) {
  1724.         return("SIGNAL OUT OF RANGE");
  1725.     } else if (!signals[sig].name) {
  1726.         return("SIGNAL UNKNOWN");
  1727.     } else return(signals[sig].name + SIG_RESERVED(sig));
  1728. }
  1729.  
  1730. static void
  1731. print_signal(sig)
  1732. int sig;
  1733. {
  1734.     if (signals[sig].action) Log(0,"%s (%d): %s\r\n",
  1735.         signal_to_string(sig),sig,signals[sig].action);
  1736. }
  1737.  
  1738. /* given signal index or name as string, */
  1739. /* returns signal index or -1 if bad arg */
  1740. static int
  1741. string_to_signal(s)
  1742. char *s;
  1743. {
  1744.     int sig;
  1745.     char *name;
  1746.  
  1747.     /* try interpreting as an integer */
  1748.     if (1 == sscanf(s,"%d",&sig)) return(sig);
  1749.  
  1750.     /* try interpreting as a string */
  1751.     for (sig=0;sig<NSIG;sig++) {
  1752.         name = signals[sig].name;
  1753.         if (SIG_RESERVED(sig)) name++;
  1754.         if (streq(s,name) || streq(s,name+3))
  1755.             return(sig);
  1756.     }
  1757.     return(-1);
  1758. }
  1759.  
  1760. /* called upon receipt of a user-declared signal */
  1761. void
  1762. exp_generic_sighandler(sig)
  1763. int sig;
  1764. {
  1765.     int proc_valid = TRUE;
  1766.  
  1767.     debuglog("generic_sighandler: handling signal(%d)\r\n",sig);
  1768.  
  1769.     if (sig < 0 || sig >= NSIG) {
  1770.         errorlog("caught impossible signal\r\n",sig);
  1771.     } else if (!signals[sig].action) {
  1772.         /* In this one case, we let ourselves be called when no */
  1773.         /* signaler predefined, since we are calling explicitly */
  1774.         /* from another part of the program, and it is just simpler */
  1775.         if (sig == 0) return;
  1776.         errorlog("caught unexpected signal: %s (%d)\r\n",
  1777.             signal_to_string(sig),sig);
  1778.     } else {
  1779.         int rc;
  1780.  
  1781. #ifdef REARM_SIG
  1782. #ifdef SYSV3
  1783.         /* assume no wait() occurs between SIGCLD and */
  1784.         /* this code */
  1785.         if (sig == SIGCLD) {
  1786.             int i, pid;
  1787.             int status;
  1788.             extern int fd_max;
  1789.  
  1790.             pid = wait(&status);
  1791.             for (i=0;i<=fd_max;i++) {
  1792.                 if (fs[i].pid == pid) break;
  1793.             }
  1794.             if (i>fd_max || !(fs[i].flags & FD_VALID)) {
  1795.                 debuglog("received SIGCLD from unknown pid %d\r\n",pid);
  1796.                 proc_valid = FALSE;
  1797.             } else {
  1798.                 fs[i].flags |= FD_SYSWAITED;
  1799.                 fs[i].wait = status;
  1800.             }
  1801.         }
  1802. #endif
  1803.         if (sig != 0) signal(sig,exp_generic_sighandler);
  1804. #endif
  1805.  
  1806.         debuglog("generic_sighandler: Tcl_Eval(%s)\r\n",signals[sig].action);
  1807.         if (proc_valid) {
  1808.           Tcl_Interp *interp = signals[sig].interp;
  1809.  
  1810.           rc = Tcl_Eval(interp,signals[sig].action,0,(char **)0);
  1811.           if (rc != TCL_OK) {
  1812.             errorlog("caught %s (%d): error in command: %s\r\n",
  1813.             signal_to_string(sig),sig,signals[sig].action);
  1814.             if (rc != TCL_ERROR) errorlog("Tcl_Eval = %d\r\n",rc);
  1815.             if (*interp->result != 0) {
  1816.             errorlog("%s\r\n",interp->result);
  1817.             }
  1818.               }
  1819.         }
  1820.     }
  1821.  
  1822.     /* if we are doing an i_read, restart it */
  1823.     if (env_valid && (sig != 0)) longjmp(env,2);
  1824. }
  1825.  
  1826. /* reset signal to default */
  1827. static void
  1828. sig_reset(sig)
  1829. int sig;
  1830. {
  1831.     RETSIGTYPE (*default_proc)();
  1832.  
  1833.     signals[sig].action = 0;  /* should've been free'd by now if nec. */
  1834.  
  1835.     /* SIGINT defaults to timeout/exit routine */
  1836.     /* Ultrix 1.3 compiler can't handle this */
  1837.     /* default_proc = (sig == SIGINT?sigint_handler:SIG_DFL);*/
  1838.     if (sig == SIGINT) default_proc = sigint_handler;
  1839.     else default_proc = SIG_DFL;
  1840.  
  1841.     signal(sig,default_proc);
  1842. }
  1843.  
  1844. /*ARGSUSED*/
  1845. int
  1846. cmdMatchMax(clientData,interp,argc,argv)
  1847. ClientData clientData;
  1848. Tcl_Interp *interp;
  1849. int argc;
  1850. char **argv;
  1851. {
  1852.     int size = -1;
  1853.     int m = -1;
  1854.     struct f *f;
  1855.     int Default = FALSE;
  1856.  
  1857.     argc--; argv++;
  1858.  
  1859.     for (;argc>0;argc--,argv++) {
  1860.         if (streq(*argv,"-d")) {
  1861.             Default = TRUE;
  1862.         } else if (streq(*argv,"-i")) {
  1863.             argc--;argv++;
  1864.             if (argc < 1) {
  1865.                 exp_error(interp,"-i needs argument");
  1866.                 return(TCL_ERROR);
  1867.             }
  1868.             m = atoi(*argv);
  1869.         } else break;
  1870.     }
  1871.  
  1872.     if (!Default) {
  1873.         if (m == -1) {
  1874.             if (!(f = exp_update_master(interp,&m,0,0)))
  1875.                 return(TCL_ERROR);
  1876.         } else {
  1877.             if (!(f = exp_fd2f(interp,m,0,0,"parity")))
  1878.                 return(TCL_ERROR);
  1879.     }
  1880.     } else if (m != -1) {
  1881.         exp_error(interp,"cannot do -d and -i at the same time");
  1882.         return(TCL_ERROR);
  1883.     }
  1884.  
  1885.     if (argc == 0) {
  1886.         if (Default) {
  1887.             size = exp_default_match_max;
  1888.         } else {
  1889.         size = f->umsize;
  1890.     }
  1891.         sprintf(interp->result,"%d",size);
  1892.         return(TCL_OK);
  1893.     }
  1894.  
  1895.     if (argc > 1) {
  1896.         exp_error(interp,"too many arguments");
  1897.         return(TCL_OK);
  1898.     }
  1899.  
  1900.     /* all that's left is to set the size */
  1901.     size = atoi(argv[0]);
  1902.     if (size <= 0) {
  1903.         exp_error(interp,"%s must be positive",EXPECT_MATCH_MAX);
  1904.         return(TCL_ERROR);
  1905.     }
  1906.  
  1907.     if (Default) exp_default_match_max = size;
  1908.     else f->umsize = size;
  1909.  
  1910.     return(TCL_OK);
  1911. }
  1912.  
  1913. /*ARGSUSED*/
  1914. int
  1915. cmdParity(clientData,interp,argc,argv)
  1916. ClientData clientData;
  1917. Tcl_Interp *interp;
  1918. int argc;
  1919. char **argv;
  1920. {
  1921.     int parity;
  1922.     int m = -1;
  1923.     struct f *f;
  1924.     int Default = FALSE;
  1925.  
  1926.     argc--; argv++;
  1927.  
  1928.     for (;argc>0;argc--,argv++) {
  1929.         if (streq(*argv,"-d")) {
  1930.             Default = TRUE;
  1931.         } else if (streq(*argv,"-i")) {
  1932.             argc--;argv++;
  1933.             if (argc < 1) {
  1934.                 exp_error(interp,"-i needs argument");
  1935.                 return(TCL_ERROR);
  1936.             }
  1937.             m = atoi(*argv);
  1938.         } else break;
  1939.     }
  1940.  
  1941.     if (!Default) {
  1942.         if (m == -1) {
  1943.             if (!(f = exp_update_master(interp,&m,0,0)))
  1944.                 return(TCL_ERROR);
  1945.         } else {
  1946.             if (!(f = exp_fd2f(interp,m,0,0,"parity")))
  1947.                 return(TCL_ERROR);
  1948.         }
  1949.     } else if (m != -1) {
  1950.         exp_error(interp,"cannot do -d and -i at the same time");
  1951.         return(TCL_ERROR);
  1952.     }
  1953.  
  1954.     if (argc == 0) {
  1955.         if (Default) {
  1956.             parity = exp_default_parity;
  1957.         } else {
  1958.             parity = f->parity;
  1959.         }
  1960.         sprintf(interp->result,"%d",parity);
  1961.         return(TCL_OK);
  1962.     }
  1963.  
  1964.     if (argc > 1) {
  1965.         exp_error(interp,"too many arguments");
  1966.         return(TCL_OK);
  1967.     }
  1968.  
  1969.     /* all that's left is to set the parity */
  1970.     parity = atoi(argv[0]);
  1971.  
  1972.     if (Default) exp_default_parity = parity;
  1973.     else f->parity = parity;
  1974.  
  1975.     return(TCL_OK);
  1976. }
  1977.  
  1978. /* following is only used as arg to tcl_error */
  1979. static char trap_usage[] = "usage: trap [[arg] {list of signals}]";
  1980.  
  1981. /*ARGSUSED*/
  1982. int
  1983. cmdTrap(clientData, interp, argc, argv)
  1984. ClientData clientData;
  1985. Tcl_Interp *interp;
  1986. int argc;
  1987. char **argv;
  1988. {
  1989.     char *action = 0;
  1990.     int n;        /* number of signals in list */
  1991.     char **list;    /* list of signals */
  1992.     int len;    /* length of action */
  1993.     int i;
  1994.     int rc = TCL_OK;
  1995.  
  1996.     if (argc > 3) {
  1997.         exp_error(interp,trap_usage);
  1998.         return(TCL_ERROR);
  1999.     }
  2000.  
  2001.     if (argc == 1) {
  2002.         for (i=0;i<NSIG;i++) if (signals[i].action) print_signal(i);
  2003.         return(TCL_OK);
  2004.     }
  2005.  
  2006.     if (argc == 3) action = argv[1];
  2007.  
  2008.     /* argv[argc-1] is the list of signals */
  2009.     /* first extract it */
  2010.     if (TCL_OK != Tcl_SplitList(interp,argv[argc-1],&n,&list)) {
  2011.         errorlog("%s\r\n",interp->result);
  2012.         exp_error(interp,trap_usage);
  2013.         return(TCL_ERROR);
  2014.     }
  2015.  
  2016.     for (i=0;i<n;i++) {
  2017.         int sig = string_to_signal(list[i]);
  2018.         if (sig < 0 || sig >= NSIG) {
  2019.             exp_error(interp,"trap: invalid signal %s",list[i]);
  2020.             rc = TCL_ERROR;
  2021.             break;
  2022.         }
  2023.  
  2024.         if (!action) action = "SIG_DFL";
  2025. /* {
  2026.             print_signal(sig);
  2027.             continue;
  2028.         }
  2029. */
  2030.  
  2031. #if 0
  2032. #ifdef HPUX
  2033.         if (sig == SIGCLD && streq(action,"SIG_DFL")) {
  2034.             action = "";
  2035.         }
  2036. #endif
  2037. #endif
  2038.  
  2039.         if (sig == SIGALRM) {
  2040.             /* SIGALRM reserved to us, for expect command */
  2041.             exp_error(interp,"trap: cannot trap SIGALRM (%d)",SIGALRM);
  2042.             rc = TCL_ERROR;
  2043.             break;
  2044.         }
  2045.  
  2046.         debuglog("trap: setting up signal %d (\"%s\")\r\n",sig,list[i]);
  2047.  
  2048.         if (signals[sig].action) free(signals[sig].action);
  2049.  
  2050.         if (streq(action,"SIG_DFL")) {
  2051.             if (sig != 0) sig_reset(sig);
  2052.         } else {
  2053.             len = 1 + strlen(action);
  2054.             if (0 == (signals[sig].action = malloc(len))) {
  2055.                 exp_error(interp,"trap: malloc failed");
  2056.                 if (sig != 0) sig_reset(sig);
  2057.                 rc = TCL_ERROR;
  2058.                 break;
  2059.             }
  2060.             memcpy(signals[sig].action,action,len);
  2061.             signals[sig].interp = interp;
  2062.             if (sig == 0) continue;
  2063.             if (streq(action,"SIG_IGN")) {
  2064.                 signal(sig,SIG_IGN);
  2065.             } else signal(sig,exp_generic_sighandler);
  2066.         }
  2067.     }
  2068.     free((char *)list);
  2069.     return(rc);
  2070. }
  2071.  
  2072. void
  2073. exp_init_expect(interp)
  2074. Tcl_Interp *interp;
  2075. {
  2076.     Tcl_CreateCommand(interp,"expect",
  2077.         cmdExpect,(ClientData)&expectCD_process,exp_deleteProc);
  2078.     Tcl_CreateCommand(interp,"expect_after",
  2079.         cmdExpectGlobal,(ClientData)&after,exp_deleteProc);
  2080.     Tcl_CreateCommand(interp,"expect_before",
  2081.         cmdExpectGlobal,(ClientData)&before,exp_deleteProc);
  2082.     Tcl_CreateCommand(interp,"expect_user",
  2083.         cmdExpect,(ClientData)&expectCD_user,exp_deleteProc);
  2084.     Tcl_CreateCommand(interp,"expect_tty",
  2085.         cmdExpect,(ClientData)&expectCD_tty,exp_deleteProc);
  2086.     Tcl_CreateCommand(interp,"match_max",
  2087.         cmdMatchMax,(ClientData)0,exp_deleteProc);
  2088.     Tcl_CreateCommand(interp,"parity",
  2089.         cmdParity,(ClientData)0,exp_deleteProc);
  2090.     Tcl_CreateCommand(interp,"trap",
  2091.         cmdTrap,(ClientData)0,exp_deleteProc);
  2092.  
  2093.     Tcl_SetVar(interp,EXPECT_TIMEOUT,    INIT_EXPECT_TIMEOUT,0);
  2094.     Tcl_SetVar(interp,SPAWN_ID_ANY_VARNAME,    SPAWN_ID_ANY_LIT,0);
  2095. }
  2096.  
  2097. void
  2098. exp_init_sig() {
  2099.     signal(SIGALRM,sigalarm_handler);
  2100.     signal(SIGINT,sigint_handler);
  2101. #if 0
  2102. #if defined(SIGWINCH) && defined(TIOCGWINSZ)
  2103.     signal(SIGWINCH,sinwinch_handler);
  2104. #endif
  2105. #endif
  2106. }
  2107.